package com.mlk.rbac.Service.impl;

import com.mlk.core.util.MD5Utils;
import com.mlk.core.util.ServerResponse;
import com.mlk.rbac.Service.LoginService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

/**
 * 系统登录
 * @author xulu
 */
@Service
public class LoginServiceImpl implements LoginService {
    /**
     * 系统登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public ServerResponse login(String username, String password) {
        if(StringUtils.isEmpty(username)){
            return ServerResponse.fail("请输入账号信息");
        }
        if(StringUtils.isEmpty(password)){
            return ServerResponse.fail("请输入密码信息");
        }

        // 进行密码的比对
        Subject subject = SecurityUtils.getSubject();
        password = MD5Utils.encode(password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
        }catch (IncorrectCredentialsException | UnknownAccountException e) {
            return ServerResponse.fail("账号或者密码不正确");
        }catch(LockedAccountException e) {
            return ServerResponse.fail("账号被冻结,请联系管理员.");
        }catch(Exception e) {
            return ServerResponse.fail("登录失败,请联系管理员.");
        }
        return ServerResponse.ok();
    }
}
